//
//  LHPhotoSelectorViewController.swift
//  图片选择器
//
//  Created by LiHong on 15/11/7.
//  Copyright © 2015年 LiHong. All rights reserved.
//

import UIKit

private let reuseIdentifier = "Cell"

class LHPhotoSelectorViewController: UICollectionViewController, LHPhotoSelectorCellDelegate {

    //MARK: - 属性
    private var layout = UICollectionViewFlowLayout()
    
    ///最大图片数
    private let maxPhotoCount = 9
    
    ///选择的图片
    var photos = [UIImage]()
    
    ///记录当前点击的cell indexpath
    var currentIndexPath: NSIndexPath?
    
    //MARK: - 构造函数
    init(){
        super.init(collectionViewLayout: layout)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        prepareCollectionView()
        

        // Do any additional setup after loading the view.
    }

    private func prepareCollectionView() {
        collectionView!.registerClass(LHPhotoSelectorCell.self, forCellWithReuseIdentifier: reuseIdentifier)
        collectionView?.backgroundColor = UIColor.whiteColor()
        layout.itemSize = CGSize(width: 80, height: 80)
        layout.sectionInset = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
    }
    
    // MARK: UICollectionViewDataSource

    override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        // #warning Incomplete implementation, return the number of sections
        return 1
    }


    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of items
        return photos.count < maxPhotoCount ? photos.count + 1 : photos.count
    }

    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! LHPhotoSelectorCell
    
        cell.backgroundColor = UIColor.brownColor()
        
        cell.cellDelegate = self
        
        if indexPath.item < photos.count {
            cell.image = photos[indexPath.item]
        } else {
            cell.setAddButton()
        }
        
        return cell
    }
    
    //MARK: - LHPhotoSelectorCellDelegate代理方法
    func  photoSelectorCellAddPhoto(cell: LHPhotoSelectorCell) {
        //判断相册是否可用
        if !UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.PhotoLibrary) {
            print("相册不可用")
            
            return
        }
        
        let picker = UIImagePickerController()
        
        picker.delegate = self
        
        currentIndexPath = collectionView?.indexPathForCell(cell)
        
        presentViewController(picker, animated: true, completion: nil)
        
    }
    
    func LHPhotoSelectorCellRemovePhoto(cell: LHPhotoSelectorCell) {
        let indexPath = collectionView!.indexPathForCell(cell)!
        
        photos.removeAtIndex(indexPath.item)
        
        if photos.count < 8 {
            collectionView?.deleteItemsAtIndexPaths([indexPath])
        } else {
            collectionView?.reloadData()
        }
        
        
    }
    
}

extension LHPhotoSelectorViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    //选择照片时的代理方法
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        
        let newImage = image.scaleImage()
        
        if currentIndexPath?.item < photos.count {
            //点击图片，替换图片
            photos[currentIndexPath!.item] = newImage
        } else {
            //点的是加号按钮
            photos.append(newImage)
        }
        
        collectionView?.reloadData()
        
        picker.dismissViewControllerAnimated(true, completion: nil)
    }
    
}

//协议
protocol LHPhotoSelectorCellDelegate: NSObjectProtocol {
    //点击添加按钮代理事件
    func photoSelectorCellAddPhoto(cell: LHPhotoSelectorCell)
    
    //点击删除按钮代理事件
    func LHPhotoSelectorCellRemovePhoto(cell: LHPhotoSelectorCell)
    
    
}

//自定义cell
class LHPhotoSelectorCell: UICollectionViewCell {
    //MARK: - 属性
    weak var cellDelegate: LHPhotoSelectorCellDelegate?
    
    //用来显示替换加好按钮的图片
    var image: UIImage? {
        didSet {
            addButton.setImage(image, forState: UIControlState.Normal)
            addButton.setImage(image, forState: UIControlState.Highlighted)
            
            removeButton.hidden = false
        }
    }
    //MARK: - 构造函数
    override init(frame: CGRect) {
        super.init(frame: frame)
        prepareUI()
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // 设置加好按钮的图片
    func setAddButton() {
        addButton.setImage(UIImage(named: "compose_pic_add"), forState: UIControlState.Normal)
        addButton.setImage(UIImage(named: "compose_pic_add_highlighted"), forState: UIControlState.Highlighted)
        
        //隐藏删除按钮
        removeButton.hidden = true
    }
    
    //MARK: - 准备UI
    private func prepareUI() {
        contentView.addSubview(addButton)
        contentView.addSubview(removeButton)
        
        addButton.translatesAutoresizingMaskIntoConstraints = false
        removeButton.translatesAutoresizingMaskIntoConstraints = false
        
        let views = ["ab" : addButton, "rb" : removeButton]
        // 添加按钮
        contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[ab]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views))
        contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[ab]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views))
        
        // 删除按钮
        contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:[rb]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views))
        contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[rb]", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views))
        
        
        
        
    }
    
    //MARK: - 按钮点击事件
    func addPhoto() {
        cellDelegate?.photoSelectorCellAddPhoto(self)
    }
    
    func removePhoto() {
        cellDelegate?.LHPhotoSelectorCellRemovePhoto(self)
    }
    
    
    //MARK: - 懒加载
    ///添加按钮
    private lazy var addButton: UIButton = {
        let button = UIButton()
        
        button.setImage(UIImage(named: "compose_pic_add"), forState: UIControlState.Normal)
        button.setImage(UIImage(named: "compose_pic_add_highlighted"), forState: UIControlState.Highlighted)
        
        button.addTarget(self, action: "addPhoto", forControlEvents: UIControlEvents.TouchUpInside)
        return button
    }()
    
    ///删除按钮
    private lazy var removeButton: UIButton = {
        let button = UIButton()
        button.setImage(UIImage(named: "compose_photo_close"), forState: UIControlState.Normal)
        button.addTarget(self, action: "removePhoto", forControlEvents: UIControlEvents.TouchUpInside)
        return button
    }()
    
    
    
}
